﻿using ConfExpert.Forms.Base;
using ConfExpert.Forms.Ceki;
using ConfExpert.Forms.ImportWizards.GomlekCekiListesi;
using ConfExpert.Properties;
using ConfExpert.Utility;
using DevExpress.XtraEditors;
using DevTeam;
using System;
using System.Data;
using System.IO;
using System.Windows.Forms;

namespace ConfExpert.Forms.Siparisler
{
    public partial class YuklenecekGomlekler : XForm
    {
        public YuklenecekGomlekler()
        {
            InitializeComponent();
            this.Text = "Çeki Listesi Hazırlama";
        }

        private void DikilenGomlekler_Load(object sender, EventArgs e)
        {
            GridManager gm = GridManager.GetManager(gridView1);
            //gm.GridMenu.AddMenu("YP'ye Ekle", Ekle, Resources.Plus_16x16);
            //gm.GridMenu.AddMenu("YP'den Çıkar", Cikar, Resources.delete_16);
            gm.GridMenu.AddMenu("Grup Oluştur", Ekle, Resources.Plus_16x16);
            gm.GridMenu.AddMenu("Gruptan Çıkar", Cikar, Resources.delete_16);
            //gm.GridMenu.AddMenu("Packing List", PL, true);    //hyperlink'e tıklayınca aç!
            //gm.GridMenu.AddMenu("Packing List- Excel", PLExcel);    //hyperlink'e tıklayınca aç!
            //if (ytk(17))
            gm.GridMenu.AddMenu("Packing List- Excel", PLExcelNew);    //hyperlink'e tıklayınca aç!

            gm.GridMenu.AddMenu("Yükleme Formu", YuklemeFormuGoster);    //hyperlink'e tıklayınca aç!

            gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
            gleAtelye.Edit.Assign(RI(Rp.Atelye));   //atölyedeki yanlış dosyalar seçilmiş olabilir, en sonunda submit etmeden yetkisi var mı diye kontrol et!
            gleCust.Edit.Assign(GetCustomGLE(ExecuteDataTable("GetMyCustomers3", WhoAmI), "Name", "CustomerId"));

            btnOzet.ItemClick += btnOzet_ItemClick;
            gleAtelye.EditValueChanged += gleAtelye_EditValueChanged;
            gleCust.EditValueChanged += gleCustomer_EditValueChanged;
            dtBaslangic.EditValueChanged += dtBaslangic_EditValueChanged;
            chkKapsam.EditValueChanged += chkKapsam_EditValueChanged;

            splitContainerControl1.AutoSize();




            if(ytk(17))
                gleCust.EditValue = 241;
            else
                gleCust.EditValue = 75;

            btnSaveIn.ItemClick += btnSaveIn_ItemClick;
            if (AppSession.InitialDirectory != null)
                btnSaveIn.Caption = AppSession.InitialDirectory;
        }

        void btnSaveIn_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FolderSelect();
        }

        void YuklemeFormuGoster(object sender, EventArgs e)
        {
            int YuklemePartisiId = gridView1.GetFocusedDataRow()["YuklemePartisiId"].ToInt();
            if (YuklemePartisiId > 0)
            {
                using (YuklemeFormu2 f = new YuklemeFormu2(YuklemePartisiId))
                    f.ShowDialog();
            }
            else
                XtraMessageBox.Show("Satır bir yükleme partisine dahil değil.");
        }

        void chkKapsam_EditValueChanged(object sender, EventArgs e)
        {
            Rfrsh();
        }

        void dtBaslangic_EditValueChanged(object sender, EventArgs e)
        {
            Rfrsh();
        }

        string mode1 = string.Empty;
        void gleCustomer_EditValueChanged(object sender, EventArgs e)
        {
            if (gleCust.EditValue != null)
            {
                mode1 = "B";
                gleAtelye.EditValue = null;
                Rfrsh();
            }
        }

        void gleAtelye_EditValueChanged(object sender, EventArgs e)
        {
            if (gleAtelye.EditValue != null)
            {
                mode1 = "A";
                gleCust.EditValue = null;
                Rfrsh();
            }
        }

        void btnOzet_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using (DikilenGomleklerOzet k = new DikilenGomleklerOzet(dtBaslangic.EditValue.ToDate(), chkKapsam.EditValue.ToStr() == "Tümü"))
                k.ShowDialog();
        }

        BindingSource bs;
        private void Rfrsh()
        {
            BindingSource bs = gridView1.Init("GetDikilenGomlek", dtBaslangic.EditValue, chkKapsam.EditValue.ToStr() == "Tümü", mode1,
                mode1 == "A" ? gleAtelye.EditValue.ToInt() : gleCust.EditValue.ToInt());
            gridView1.AddDetailGrid(gridView2, "DosyaNo");  // + (mode1 == "A" ? "CustomerId" : "AtelyeId"));
            bs.Filter = "DosyaNo like 'F%' OR DosyaNo like 'K%' OR DosyaNo like 'D%'";

            gridView1.MakeColumnInvisible("PlanlamaId");
            gridView1.FormatAsNumber(0, "Toplam");
            gridView1.AddSummary("Toplam");
            gridView2.FormatAsNumber(0, "SipAdet");
            gridView2.AddSummary("SipAdet");
            gridView1.BestFitColumns();
            gridView2.BestFitColumns();
        }

        void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gridView2.BestFitColumns();
        }

        void Ekle(object sender, EventArgs e)
        {
            EkleCikar("Ekle");
        }

        void Cikar(object sender, EventArgs e)
        {
            EkleCikar("Cikar");
        }

        private void EkleCikar(string mode2)
        {
            if (gridView1.SelectedRowsCount < 1)
                gridView1.SelectRow(gridView1.FocusedRowHandle);

            string PlanlamaIds = gridView1.GetSelectedValues("PlanlamaId");
            object YuklemePartisiId = ExecuteScalar("UpdYuklemePartisi", PlanlamaIds, mode2, WhoAmI);

            foreach (int rh in gridView1.GetSelectedRows())
                gridView1.SetRowCellValue(rh, "YuklemePartisiId", YuklemePartisiId);    //çıkar'da ne olur??

            string DosyaNo = gridView1.GetFocusedDataRow()["DosyaNo"].ToStr();

            gridView1.FocusedRowHandle = gridView1.LocateByValue("DosyaNo", DosyaNo);
            gridView2.BestFitColumns();

            if (mode2 == "Ekle")
            {
                //using (YuklemeFormu2 f = new YuklemeFormu2(YuklemePartisiId.ToInt()))
                //    if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)

                int CustomerId = gleCust.EditValue.ToInt();
                int YPId = YuklemePartisiId.ToInt();
                XPL a = new XPL();
                switch (CustomerId)
                {
                    case 075: a = new PL_Westbrook(PlanlamaIds, YPId); break;
                    case 178: a = new PL_Hackett(PlanlamaIds, YPId); break;
                    case 241: a = new PL_HolyFashion(PlanlamaIds, YPId); break;
                    case 431: a = new PL_Faconnable(PlanlamaIds, YPId); break;

                    default:
                        //PL px = new PL(this);
                        break;
                }

                if (a.dx.Count > 0)
                    PLExcelNew(null, null);
            }
        }

        //void PL(object sender, EventArgs e)
        //{
        //    int YuklemePartisiId = gridView1.GetFocusedDataRow()["YuklemePartisiId"].ToInt();
        //    if (YuklemePartisiId > 0)
        //        AppSession.MainForm.ShowMdiChildForm(typeof(PackingList), YuklemePartisiId);
        //    else
        //        XtraMessageBox.Show("Yükleme Partisi oluşturulmuş satırların çeki listesi alınabilir.");
        //}

        string FolderSelect()
        {
            FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
            //folderBrowserDialog1.Description = "Select the directory that you want to use.";

            // Do not allow the user to create new files via the FolderBrowserDialog.
            folderBrowserDialog1.ShowNewFolderButton = true;

            // Default to the My Documents folder.
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.DesktopDirectory;

            DialogResult result = folderBrowserDialog1.ShowDialog();
            if (result == DialogResult.OK)
            {
                btnSaveIn.Caption =
                    AppSession.InitialDirectory = folderBrowserDialog1.SelectedPath;
            }

            return AppSession.InitialDirectory;
        }

        void PLExcelNew(object sender, EventArgs e)
        {
            int YuklemePartisiId = gridView1.GetFocusedDataRow()["YuklemePartisiId"].ToInt();
            if (YuklemePartisiId > 0)
            {
                if (AppSession.InitialDirectory == null)
                    FolderSelect();

                int CustomerId = gleCust.EditValue.ToInt();
                PackingListNew pl = new PackingListNew(YuklemePartisiId);

                pl.Save();
            }
        }

        void PLExcel(object sender, EventArgs e)
        {
            int YuklemePartisiId = gridView1.GetFocusedDataRow()["YuklemePartisiId"].ToInt();
            if (YuklemePartisiId > 0)
            {
                DataSet d = ExecuteDataSet("GetPackingList", YuklemePartisiId, string.Empty, WhoAmI);

                // Create a simple workbook.
                SpreadsheetGear.IWorkbook workbook = SpreadsheetGear.Factory.GetWorkbook();



                //TODO! Template kullanılmazsa bundan sonraki 3 komut da olmayacak!
                DataTable t = Session.DataManager.ExecuteDataTable("GetTemplates", "CekiListesi", 1 /*WB için*/);

                // Save the workbook to a memory stream.
                System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(t.Rows[0]["BLOB"] as byte[]);

                // Create another workbook from the memory stream.
                workbook = SpreadsheetGear.Factory.GetWorkbookSet().Workbooks.OpenFromStream(memoryStream);



                DataTable dtSheet = d.Tables[0];
                DataTable dtList = d.Tables[1];
                if (dtSheet.Rows.Count > 0)
                {
                    for (int i = 1; i < dtSheet.Rows.Count; i++)    //1 sheet zaten var
                        workbook.Worksheets["PL"].CopyBefore(workbook.Worksheets["PL"]);


                    for (int i = 0; i < dtSheet.Rows.Count; i++)
                    {
                        SpreadsheetGear.IWorksheet worksheet = workbook.Worksheets[i];
                        SpreadsheetGear.IRange cells = worksheet.Cells;

                        worksheet.Name = "PL "
                            + dtSheet.Rows[i]["SayfaAdi"].ToStr()
                            + (dtSheet.Rows[i]["Termin"] != DBNull.Value ? string.Format(" {0:00}.{1:00}", dtSheet.Rows[i]["Termin"].ToDate().Day, dtSheet.Rows[i]["Termin"].ToDate().Month) : string.Empty).Replace("  ", " ");

                        worksheet.Tab.ColorIndex = 42 + i;

                        int DagilimId = dtSheet.Rows[i]["DagilimId"].ToInt();
                        DataRow r = AppSession.Lookups.Dagilim.FindByDagilimId(DagilimId);
                        int basla = dtSheet.Rows[i]["Basla"].ToInt();
                        int bitir = dtSheet.Rows[i]["Bitir"].ToInt();
                        int silinensutunsayisi = 15 - bitir + basla;

                        cells[0, 9, 0, 24].UnMerge();   //SIZES
                        cells[2, 0, 5, 0].UnMerge();
                        cells[2, 26, 5, 26].UnMerge();

                        DataRow[] rs = dtList.Select("PackingListId=" + dtSheet.Rows[i]["PackingListId"]);

                        for (int j = 1; j < (rs.Length - 1) / 4 + 1; j++)
                        {
                            //for (int z = 0; z < 4; z++)
                            //    cells["7:7"].Insert(shiftDirection: InsertShiftDirection.Down);

                            cells["3:6"].Copy(cells[4 * j + 2, 0, 4 * j + 5, 0]);
                            cells["AA" + (4 * j + 2)].Formula = "=SUM(Z" + (4 * j + 2) + ":Z" + (4 * j + 5) + ")";
                            cells[4 * j + 2, 0, 4 * j + 5, 0].Merge();
                            cells[4 * j + 2, 26, 4 * j + 5, 26].Merge();
                            //cells["AA" + 4 * j + 2 + ":AA" + 4 * j + 5].Formula = "=SUM(Z" + 4 * j + 2 + ":Z" + 4 * j + 5 + ")";
                        }
                        cells["AA2:AA5"].Formula = "=SUM(Z2:Z5)";
                        cells[2, 0, 5, 0].Merge();
                        cells[2, 26, 5, 26].Merge();


                        for (int j = 0; j < silinensutunsayisi; j++)
                            cells["K:K"].Delete();  //fazla beden sütunlarını sil

                        for (int j = basla; j <= bitir; j++)
                            cells[1, 9 + j - basla].Value = r[string.Format("A{0:00}", j)];

                        cells[0, 9, 0, 24 - silinensutunsayisi].Merge();  //SIZES hücrelerini merge et


                        for (int j = 0; j < rs.Length; j++)
                        {
                            DataRow rx = rs[j];
                            cells["A" + (j + 3)].Value = rx["BigBoxNr"].ToStr();
                            cells["B" + (j + 3)].Value = rx["BoxNr"].ToStr();
                            cells["C" + (j + 3)].Value = rx["Model"].ToStr();
                            cells["D" + (j + 3)].Value = rx["Ek4"].ToStr();
                            cells["E" + (j + 3)].Value = rx["Magaza"].ToStr();
                            cells["F" + (j + 3)].Value = rx["Ek1"].ToStr();     //TODO!
                            cells["G" + (j + 3)].Value = rx["Ulke"].ToStr();
                            cells["H" + (j + 3)].Value = rx["Ek2"].ToStr();
                            cells["I" + (j + 3)].Value = rx["Ek3"].ToStr();
                            cells[j + 2, 12 + bitir - basla].Value = rx["DosyaNo"].ToStr();

                            for (int j2 = basla; j2 <= bitir; j2++)
                                cells[j + 2, 9 + j2 - basla].Value = rx[string.Format("A{0:00}", j2)];

                        }

                        cells["A:Z"].Columns.AutoFit();
                        for (int col = 0; col < worksheet.UsedRange.ColumnCount; col++)
                            cells[1, col].ColumnWidth *= 1.13;

                        //workbook.Names["BIG_BOX_NO"].RefersToRange.ColumnWidth =
                        //workbook.Names["BOX_NO"].RefersToRange.ColumnWidth =
                        //workbook.Names["BIG_BOX_TOT"].RefersToRange.ColumnWidth = 10;

                        //IBorder brd = worksheet.UsedRange.Borders[BordersIndex.EdgeBottom | BordersIndex.EdgeLeft | BordersIndex.EdgeRight | BordersIndex.EdgeTop];
                        //brd.LineStyle = SpreadsheetGear.LineStyle.Continous;
                        //brd.Weight = SpreadsheetGear.BorderWeight.Thin;


                    }
                }





                System.IO.MemoryStream memoryStream2 = new System.IO.MemoryStream();
                workbook.SaveToStream(memoryStream2, SpreadsheetGear.FileFormat.OpenXMLWorkbook);

                // Close the workbook.
                workbook.Close();

                string FN = ExecuteScalar("GetPLFilename", YuklemePartisiId).ToStr();

                if (sender == null)
                {
                    SaveFileDialog sfd = new SaveFileDialog();
                    sfd.Filter = "Excel Dosyaları|*.xlsx";
                    sfd.FileName = FN;
                    if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                    {
                        //byte[] sablon = (byte[])ExecuteDataTable("DX_GetSablon").Rows[0][0];
                        //File.WriteAllBytes(sfd.FileName, sablon);
                        //FileManager.RunFile(sfd.FileName);

                        Ac(memoryStream2, sfd.FileName);
                    }
                }
                else
                {
                    FN = FileManager.GetTempFolder() + FN + ".xlsx";
                    Ac(memoryStream2, FN);
                }

            }
            else
                XtraMessageBox.Show("Yükleme Partisi oluşturulmuş satırların çeki listesi alınabilir.");
        }

        private void Ac(System.IO.MemoryStream memoryStream2, string FN)
        {
            byte[] BLOB = memoryStream2.ToArray();
            System.Diagnostics.Process process = new System.Diagnostics.Process();
            process.StartInfo.FileName = ByteArrayToFile3(FN, BLOB);
            process.Start();
        }

        public string ByteArrayToFile3(string filePath, byte[] content)
        {
            string FullPath = filePath; //System.Environment.GetFolderPath(System.Environment.SpecialFolder.InternetCache) + "\\" + filePath;
            using (FileStream fs = new FileStream(FullPath, FileMode.Create, FileAccess.Write))
            using (BinaryWriter bw = new BinaryWriter(fs))
            {
                bw.Write(content);
                bw.Flush();
            }

            return FullPath;
        }


    }
}
